const { Add, Update, QueryOne, QueryById, Exec_Count, Query, Exec } = require('../db/dbhelper');
var { init, format } = require('../models/tasktodo');
var { formatDateYear, formatDateTime } = require('../libs/common');
var _ = require('underscore');
const logger = require('../libs/log').logger;
var { sendMsg } = require('./wechat');
var moment = require('moment');

//新增
const taskAdd = function (doc) {
  try {
    let new_doc =  init(doc);
    return Add('hzz_tasktodos', new_doc);
  } catch (error) {
    logger.error('----taskAdd-----,error',error);
    
  }
}

//处理
const taskDone = async function (doc) {
  try {
    logger.error('----taskDone-----,doc',doc);
    let data= await QueryById('hzz_tasktodos', doc.id);
    if(data.name=='用户确认'){
      let fuser = await QueryOne('hzz_peoples',{code: data.gcode},'id,invitcode,cross_realname_auth,grade');
      let invister;
      if(fuser){
        invister = await QueryOne('hzz_peoples',{code: fuser.invitcode},'nickname');
      }
      
      if(doc.status==1){
        doc.message = '用户已确认';
        // 判断用户是否实名认证
        if(fuser.cross_realname_auth !=1){
          return {
            code: 1,
            msg: '请协助用户先完成实名认证！'
          }
        }
        await Update('hzz_peoples',{id: fuser.id, confirm: 1, userstate: 0, grade: (fuser.grade||0)+1});
        if(invister){
          // 发送提醒消息 
          let send_data = {
            "first": {
              "value": "您好，您的业务有新进展！",
              "color": "#173177"
            },
            "keyword1": {
              "value": "新用户确认",
              "color": "#173177"
            },
            "keyword2": {
              "value": `推荐人[${invister.nickname}]已确认您的好友身份，请完善个人资料，找到心仪的TA吧！`,
              "color": "#74BB44"
            },
            "remark": {
              "value": "点击查看并处理",
              "color": "#173177"
            }
          };
          let send_data_red = {
            "thing2": {
              "value": `推荐人[${invister.nickname}]已确认您的好友身份，请完善个人资料，找到心仪的TA吧！`
            },
            "time1": {
              "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
            }
          };
          sendMsg('user_confirm', send_data, data.gcode,"pages/myInfo/myInfo",send_data_red); //- todo  我的主页
        }
      }else{
        doc.message = '用户已拒绝';
        // 发送提醒消息 
        let send_data = {
          "first": {
            "value": "您好，您的业务有新进展！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "新用户确认",
            "color": "#173177"
          },
          "keyword2": {
            "value": `您的推荐人[${invister.nickname}]未确认您的好友身份，请联系TA或客服咨询。`,
            "color": "#e8320e"
          },
          "remark": {
            "value": "点击查看并处理",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": `您的推荐人[${invister.nickname}]未确认您的好友身份，请联系TA或客服咨询。`
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('user_confirm', send_data, data.gcode,"pages/myInfo/myInfo",send_data_red);//- todo  我的主页
      }
    }else if(data.name=='相册解锁'){
      let puser = await QueryOne('hzz_peoples',{code: data.pcode},'nickname');
      if(doc.status ==1){
        doc.message = '相册解锁已通过';
        // 发送提醒消息 
        let send_data = {
          "first": {
            "value": "您好，您的业务有新进展！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "相册解锁消息",
            "color": "#173177"
          },
          "keyword2": {
            "value": `您申请查看[${puser.nickname}]的相册已通过，快去看看TA吧！`,
            "color": "#74BB44"
          },
          "remark": {
            "value": "点击查看并处理",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": `您申请查看[${puser.nickname}]的相册已通过，快去看看TA吧！`
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('photo_tmpid', send_data, data.gcode,"pages/index/index",send_data_red);
      }else{
        doc.message = '相册解锁已拒绝';
        // 发送提醒消息 
        let send_data = {
          "first": {
            "value": "您好，您的业务有新进展！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "相册解锁消息",
            "color": "#173177"
          },
          "keyword2": {
            "value": `您申请查看[${puser.nickname}]的相册未通过，再去看看其他人吧！`,
            "color": "#e8320e"
          },
          "remark": {
            "value": "点击查看并处理",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": `您申请查看[${puser.nickname}]的相册未通过，再去看看其他人吧！`
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('photo_tmpid', send_data, data.gcode,"pages/index/index",send_data_red);
      }
    }else if(data.name=='推荐人申请'){
      let fuser = await QueryOne('hzz_peoples',{code: data.gcode},'id,nickname,confirm,isinviter,cross_realname_auth');
      let invit = await QueryOne('hzz_inviterhistories',{pcode: data.gcode});
      if(doc.status ==1){
        doc.message = '推荐人已确认';
        if(fuser.cross_realname_auth !=1){
          return {
            code: 1,
            msg: '请协助用户先完成实名认证！'
          }
        }
        await Update('hzz_peoples',{id: fuser.id, confirm: 1, visterstate: 0});//isinviter: 1, level: 9
        if(invit){
          await Update('hzz_inviterhistories',{id: invit.id, isconfirm: 1, updatetime: new Date()});
        }
        
        // 发送提醒消息 
        let send_data = {
          "first": {
            "value": "您好，您的业务有新进展！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "推荐人申请结果",
            "color": "#173177"
          },
          "keyword2": {
            "value": `您的推荐人申请已获邀请人确认，请耐心等待平台审核通过！`,
            "color": "#74BB44"
          },
          "remark": {
            "value": "将二维码分享给征婚人，邀请TA来脱单",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": `您的推荐人申请已获邀请人确认，请耐心等待平台审核通过！`
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('photo_tmpid', send_data, data.gcode,"pages/index/index",send_data_red);
      }else{
        doc.message = '推荐人申请已拒绝';
        if(invit){
          await Update('hzz_inviterhistories',{id: invit.id,  isconfirm: 9, updatetime: new Date()});
        }
        // 发送提醒消息 
        let send_data = {
          "first": {
            "value": "您好，您的业务有新进展！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "推荐人申请结果",
            "color": "#173177"
          },
          "keyword2": {
            "value": `您的推荐人申请被邀请人拒绝，联系TA询问原因吧！ `,
            "color": "#e8320e"
          },
          "remark": {
            "value": "点击查看并处理",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": `您的推荐人申请被邀请人拒绝，联系TA询问原因吧！ `
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('photo_tmpid', send_data, data.gcode,"pages/index/index",send_data_red);
      }
    }
    await  Update('hzz_tasktodos', format(doc));
    return {
      code: 0,
      msg: '处理成功'
    }
  } catch (error) {
    logger.error('----taskDone-----,error',error);
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

//列表
const taskList = async function (doc) {
  try {
    logger.error('----taskList-----,doc',doc);
    let pdata = await QueryOne('hzz_peoples',{code: doc.pcode});
    let list= await Exec(`select * from hzz_tasktodos where pcode='${doc.pcode}'  AND length(gcode)=12 ORDER BY status ASC, createtime DESC,id ASC`);
    for (let index = 0; index < list.length; index++) {
      let item = list[index];
      let gdata = await QueryOne('hzz_peoples',{code: item.gcode},'name,nickname,grender,avator,name_father,identity,birthday,height,city');
      if(gdata){
        if(pdata.isinviter){
          if(gdata.identity=='家长'){
            gdata.nickname = gdata.name_father? gdata.name_father: gdata.nickname;
          }else{
            gdata.nickname = gdata.name? gdata.name: gdata.nickname;
          }
        }
        
        if(gdata.nickname && gdata.nickname.length>6){
          gdata.nickname= gdata.nickname.substr(0,6);
        }

        gdata.birthday = formatDateYear(gdata.birthday);
        if(gdata.city){
          gdata.city = '现居'+gdata.city.replace('市','');
        }else{
          gdata.city='';
        }

        // 用户没有头像，采用默认头像
        if(!gdata.avator){
          gdata.avator = gdata.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png': 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
        }
      }
      
      item.gdata = gdata || {};
      item.code = item.gcode;
      item.updatetime = formatDateTime(item.createtime);
      delete item.gcode;
      delete item.pcode;
      delete item.createtime;
    }
    let rdata= {
      code: 0,
      data: list,
      msg: list.length ? '获取成功':'暂无待办信息'
    }
    logger.error('----taskList-----,rdata',rdata);
    return rdata;
  } catch (error) {
    logger.error('----taskList-----,error',error);
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

module.exports = {
  taskAdd,
  taskDone,
  taskList
}